from django.shortcuts import render,redirect
from django.http import HttpResponse
from .models import User
import hashlib

# Create your views here.
def index(request):
    # 假设 服务端判断 request.cookie['session_id'],session_id没有或错误禁止登陆
    # print(request.session['is_login'])
    return render(request, 'login/index.html', context={})


def reqister(request):
    pass

def register_check(request):
    """检查注册参数，返回json结果
    :param   客户端的表单请求
    :method  请求方式  POST
    :return  json格式的字符串
    '
    {
        "code":100,              #200成功
        "status":"faild",        #ok成功
        "error_message":"",      #用户名太短  等。。。
    }'
    """
    import json
    resp_obj = {}
    name = request.POST['name']
    # 验证长度范围
    if len(name) <= 1:
        resp_obj = {
            'code': 100,
            'status': '验证失败',
            'error_message': '用户名太短'
        }
        resp_json = json.dumps(resp_obj)
        print(type(resp_obj))
        print(type(resp_json))
        return HttpResponse(resp_json)


# 注册
def register(request):
    """GET  返回注册表单"""
    if request.method == 'GET':
        return render(request, 'login/register.html', context={})
    elif request.method == 'POST':
        context={}
        name = request.POST['name']
        password = request.POST['password']

        # 验证用户名,密码是否在长度范围内 len()
        # 判断字符串为纯中文
        pass
        # return render(request, 'login/register.html', context)  # 失败

        # 密码加密     也可以 from django.contrib.auth.hashers import make_password,check_password
        md5 = hashlib.md5()
        md5.update(password.encode())
        hash_password = md5.hexdigest()



        user = User(name=name,password=password,hash_password=hash_password)
        user.save()
        return redirect(to='/login/index/')



def do_register(request):
    pass


# 登录
def login(request):
    if request.method == 'GET':
        return render(request,'login/login.html',context={})
    elif request.method == 'POST':
        context={}
        name = request.POST['name']
        password = request.POST['password']

        # 判断字符串是否是中文


        user_list = User.objects.filter(name=name,password=password)  # 多个where条件逗号分割, 代表and连接条件
        # 多条件可以用Q对象.from django.db.models import Q
        #  User.objects.filter(Q{name=111}&Q{password=111})
        if user_list:
            # 登陆成功

            # 原理
            # user_list[0].name + time.now() 通过hash生成session_id
            # return HttpResponse set_cookie  {'session_id':'fdsggdsgds'}
            # 客户端接收到响应 根据set_cookie响应头把数据存到自己的cookie中
            # 之后客户端每一次请求, 都会带上cookie,服务器就会比对是否存在,存在即用户已登陆
            # django已经封装了方法,我们可以简单在响应头里设置cookie


           # # request.session['is_login'] = True
            ## request.session['username'] = user_list[0].name
            ## request.COOKIES['is_login'] = True
            ## request.COOKIES['username'] = user_list[0].name
           # # context = {'message':'d登录成功'}
           # # return render(request,'login/index.html',context)

            return redirect(to='/login/index/')
        else:
            # 登陆失败
            if User.objects.filter(name=name).exist():
                context['message'] = '密码错误'
                return render(request,'login/login.html',context)
            else:
                context['message'] = '用户名不存在,请先注册'
                return render(request,'login/login.html',context)


def do_login(request):
    pass

def logout(request):
    pass